package com.zc.emos.wx.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zc.emos.wx.db.dao.TbDeptDao;
import com.zc.emos.wx.db.dao.TbUserDao;
import com.zc.emos.wx.db.pojo.MessageEntity;
import com.zc.emos.wx.db.pojo.TbUser;
import com.zc.emos.wx.exception.EmosException;
import com.zc.emos.wx.service.UserService;
import com.zc.emos.wx.task.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName UserServiceImpl.java
 * @Description TODO
 * @createTime 2021年12月22日 13:23:00
 */
@Service
@Slf4j
@Scope("prototype")
public class UserServiceImpl implements UserService {

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private TbUserDao userDao;

    @Autowired
    private MessageTask messageTask;

    @Autowired
    private TbDeptDao deptDao;

    private String getOpenId(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        System.out.println(appId+"appsecret"+appSecret+"code:"+code);
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openid = json.getStr("openid");
        System.out.println("openId:"+openid);
        if(openid ==null || openid.length() == 0){
            throw new RuntimeException("临时登录凭证错误；");
        }
        return openid;
    }

    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
        if(registerCode.equals("000000")){
            boolean bool = userDao.haveRootUser();
            if(!bool){
                String openId = getOpenId(code);
                HashMap param = new HashMap();
                param.put("openId", openId);
                param.put("nickname", nickname);
                param.put("photo", photo);
                param.put("role", "[0]");
                param.put("status", 1);
                param.put("createTime", new Date());
                param.put("root", true);
                userDao.insert(param);
                int id = userDao.searchIdByOpenId(openId);


                MessageEntity entity = new MessageEntity();
                entity.setSenderId(0);
                entity.setSenderName("系统消息");
                entity.setUuid(IdUtil.simpleUUID());
                entity.setMsg("欢迎您注册成为超级管理员， 请及时更新您的员工信息。");
                entity.setSendTime(new Date());
                messageTask.sendAsync(id+ "", entity);
                return id;
            }else {
                throw new EmosException("无法绑定超级管理员账号");
            }
        }else{
            //普通员工的注册
        }
        return 0;
    }

    @Override
    public Set<String> searchUserPermissions(int userId) {
        Set<String> permissions = userDao.searchUserPermissions(userId);
        return permissions;
    }

    @Override
    public Integer login(String code) {
        String openId = getOpenId(code);
        Integer id = userDao.searchIdByOpenId(openId);
        if (null == id) throw new EmosException("账户不存在");

        //  从消息队列中接收信息 ，转移到消息表
//        messageTask.receiveAsync(id+"");
        return id;
    }

    @Override
    public TbUser searchById(int userId) {
        return userDao.searchById(userId);
    }

    @Override
    public String searchUserHiredate(int userId) {

        String hiredate = userDao.searchUserHiredate(userId);
        return hiredate;
    }

    @Override
    public HashMap searchUserSummary(int userId) {
        return userDao.searchUserSummary(userId);
    }


    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {

        ArrayList<HashMap> list1 = deptDao.searchDeptMembers(keyword);
        ArrayList<HashMap> list2 = userDao.searchUserGroupByDept(keyword);
        //循环遍历比较  若某个员工的deptId 属于 一个deptId  就将该员工添加到该部门
        for (HashMap map1 : list1) {
            long deptId = (long) map1.get("id");//获取部们的Id
            ArrayList members = new ArrayList<>();
            for (HashMap map2 : list2) {
                long id = (long) map2.get("deptId");//获取员工所属的部门Id和部门id比较
                if (deptId == id) {
                    members.add(map2); //一致添加到集合
                }
            }
            map1.put("members", members);
        }

        return list1;
    }

    @Override
    public ArrayList<HashMap> searchMembers(List param) {
        ArrayList<HashMap> list = userDao.searchMembers(param);
        return list;
    }

    @Override
    public List<HashMap> selectUserPhotoAndName(List param) {
        List<HashMap> list=userDao.selectUserPhotoAndName(param);
        return list;
    }

    @Override
    public String searchMemberEmail(int id) {
        String email=userDao.searchMemberEmail(id);
        return email;
    }


}
